﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using VPLink2013.Framework;

namespace VPLink2013.Webpart
{
    public class SyndicatsNewsList : WebpartVPLink
    {
        private string strList = "News";

        #region get HTML
        /// <summary>
        /// Returns the HTML code rendered by this web part
        /// </summary>
        /// <returns>HTL code as string</returns>
        protected override string GetHtml()
        {
            string strHtml = string.Empty;
            ContextTrace.PrefixFileName = "webpart SyndicatsNewsList";

            try
            {
                //SPSecurity.RunWithElevatedPrivileges
                //(delegate()
                //{

                global = new GlobalVPLink2013();
                global.ListeAnnonces = new List<Annonce>();

                string strUrl = SPContext.Current.Web.Url;
                ContextTrace.AddTrace("strUrl : " + strUrl);
                string strXslFileName = "";
                using (SPSite site = new SPSite(strUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        //if (this.Title.StartsWith("CFDT"))
                        //{
                        //    strList = "CFDT";
                        //}
                        //if (this.Title.StartsWith("CGT"))
                        //{
                        //    strList = "CGT";
                        //}
                        strList = this.Title;
                        ContextTrace.PrefixFileName = "Syndicats - " + strList;

                        ContextTrace.AddTrace("strList : " + strList);
                        SPList lst = web.Lists[strList];

                        string strID = ParamFrm("ItemID");
                        if (strID == "")
                        {
                            strID = ParamFrm("ID");
                        }

                        if (strID == "")
                        {
                            strXslFileName = "SyndicatsNewsList.xsl";
                            ProcessNewsList(lst);
                        }
                        else
                        {
                            strXslFileName = "SyndicatsNewsDetail.xsl";
                            ProcessNewsDetail(lst, strID);
                        }
                    }

                    string strXml = FileSerialization.CreateXmlStringFromObj(global);

                    string strXslPath = pathVP + @"\XSL\NewsVP\" + strXslFileName;
                    ContextTrace.AddTrace("GetHtml.strXslPath = " + strXslPath);
                    string login = VPLink2013XsltTransformHelper.StringAfter(this.Context.User.Identity.Name);
                    strHtml = VPLink2013XsltTransformHelper.GetTransform(strXml, strXslPath, login, pathTemp);
                }
                //});
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("Erreur GetHtml : " + exc.Message + "/" + exc.StackTrace);
            }
            return strHtml;
        }
        #endregion get HTML

        private void ProcessNewsList(SPList lst)
        {
            string strListe = lst.Title;
            SPQuery spQuery = new SPQuery();
            spQuery.RowLimit = 3000;
            StringBuilder sb = new StringBuilder();

            MenuInterneAnnonce mei = new MenuInterneAnnonce();

            global.Filtre = new Filtre();
            global.Filtre.Titre = ParamFrm("FiltreNewsTitre");
            if (global.Filtre.Titre == "Rechercher des news")
            {
                global.Filtre.Titre = string.Empty;
            }

            string strDateCrt = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now);
            //if (global.Filtre.Titre != "")
            //{
            //    sb.Append("<Where>");
            //    sb.AppendLine("<Or>");
            //    sb.AppendLine("     <Contains><FieldRef Name='Title'/><Value Type='Text'>" + global.Filtre.Titre + "</Value></Contains>");
            //    sb.AppendLine("     <Contains><FieldRef Name='Description'/><Value Type='Text'>" + global.Filtre.Titre + "</Value></Contains>");
            //    sb.AppendLine("</Or>");
            //    sb.AppendLine("</Where>");
            //}

            string strDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now);
            sb.AppendLine("<Where>");
            sb.AppendLine("         <Leq><FieldRef Name='Date_x0020_publication'/><Value Type='DateTime' IncludeTimeValue='True'>" + strDate + "</Value></Leq>");
            sb.AppendLine("</Where>");
            sb.AppendLine("<OrderBy><FieldRef Name='Date_x0020_publication' Ascending='FALSE'/><FieldRef Name='ID' Ascending='FALSE'/></OrderBy>");

            if (global.Filtre.Titre == "")
            {
                global.Filtre.Titre = "Rechercher une news";
            }
            string Query = sb.ToString();
            spQuery.Query = Query;
            ContextTrace.AddTrace("spQuery.Query : " + spQuery.Query);


            SPListItemCollection items = lst.GetItems(spQuery);
            ContextTrace.AddTrace("items.Count : " + items.Count.ToString());

            string strPageCrt = ParamFrm("PageCrt");

            int iPageCrt = 1;
            if (strPageCrt != "")
            {
                iPageCrt = int.Parse(strPageCrt);
            }
            global.Filtre.PageCrt = GetControlHidden("PageCrt", iPageCrt.ToString());

            int iPagePrec = 0;
            int iPageSuiv = 0;

            int iNbPerPage = 4;

            int iCrt = 1;
            int iStart = (iPageCrt - 1) * iNbPerPage + 1;
            int iEnd = iPageCrt * iNbPerPage;

            ContextTrace.AddTrace("iStart : " + iStart.ToString());
            ContextTrace.AddTrace("iEnd : " + iEnd.ToString());

            foreach (SPListItem item in items)
            {
                ContextTrace.AddTrace("iCrt : " + iCrt.ToString());
                if (iCrt < iStart)
                {
                    iPagePrec = iPageCrt - 1;
                    ContextTrace.AddTrace("iPagePrec : " + iPagePrec.ToString());
                }
                if (iCrt > iEnd)
                {
                    iPageSuiv = iPageCrt + 1;
                    ContextTrace.AddTrace("iPageSuiv : " + iPageSuiv.ToString());
                }
                if (iCrt >= iStart && iCrt <= iEnd)
                {
                    ContextTrace.AddTrace("-------------------------------");

                    Annonce ann = new Annonce();
                    ann.ID = item.ID.ToString();
                    ann.LinkDetail = ParamSharepointSite + "/syndicats/Pages/" + lst + "NewsDetail.aspx?ItemID=" + ann.ID;
                    if (strList == "News")
                    {
                        ann.DatePublication = VPLink2013SPHelper.GetValueDate(item, "Date publication");
                    }
                    ann.Titre = VPLink2013SPHelper.GetValue(item, "Titre");
                    ann.TitrePiwik = ann.Titre.Replace("/", "-").Replace("'", "\\'").Replace("\"", "\\'");
                    ann.Chapeau = VPLink2013SPHelper.GetValue(item, "Chapeau");
                    ann.Body = VPLink2013SPHelper.GetValue(item, "Description");
                    ann.DatePublication = VPLink2013SPHelper.GetValueDate(item, "Date publication");

                    ann.Attachments = FormatDetailAttachments(item, false);
                    /*if (lst.Title == "CGT")
                    {
                        ann.Surtitre = "CGT";
                    }
                    if (lst.Title == "CFDT")
                    {
                        ann.Surtitre = "CFDT";
                    }
					 * */
                    ann.Surtitre = lst.Title;
                    ann.Photo1 = VPLink2013SPHelper.GetValuePhoto(item, "Photo");

                    ContextTrace.AddTrace("ann.ID : " + ann.ID);
                    ContextTrace.AddTrace("ann.Titre : " + ann.Titre);
                    ContextTrace.AddTrace("ann.Chapeau : " + ann.Chapeau);
                    ContextTrace.AddTrace("ann.Photo1 : " + ann.Photo1);
                    ContextTrace.AddTrace("ann.Surtitre : " + ann.Surtitre);

                    global.ListeAnnonces.Add(ann);
                }
                iCrt += 1;
            }

            if (iPagePrec > 0 || iPageSuiv > 0)
            {
                StringBuilder sbNavigationPages = new StringBuilder();
                sbNavigationPages.AppendLine("<div>");

                if (iPagePrec > 0)
                {
                    sbNavigationPages.AppendLine("<a href=\"javascript:GoToPage(" + iPagePrec.ToString() + ");\">");
                    sbNavigationPages.AppendLine("<img src=\"/_layouts/15/VPLink2013/Images/pages_news_left.jpg\" width=\"6\" height=\"11\" border='0'>");
                    sbNavigationPages.AppendLine("   Page précédente");
                    sbNavigationPages.AppendLine("</a>");
                }
                if (iPagePrec > 0 && iPageSuiv > 0)
                {
                    sbNavigationPages.AppendLine("<span>|</span>");
                }
                if (iPageSuiv > 0)
                {
                    sbNavigationPages.AppendLine("<a href=\"javascript:GoToPage(" + iPageSuiv.ToString() + ");\">");
                    sbNavigationPages.AppendLine("Page suivante   ");
                    sbNavigationPages.AppendLine("<img src=\"/_layouts/15/VPLink2013/Images/pages_news_right.jpg\" width=\"6\" height=\"11\" border='0'>");
                    sbNavigationPages.AppendLine("</a>");
                }
                sbNavigationPages.AppendLine("</div>");

                global.Filtre.NavigationPages = sbNavigationPages.ToString();
                global.Filtre.NavigationPagesBottom = sbNavigationPages.ToString();
                ContextTrace.AddTrace("global.Filtre.NavigationPages : " + global.Filtre.NavigationPages);
            }
        }

        private void ProcessNewsDetail(SPList lst, string strID)
        {
            try
            {
                int idChantier = int.Parse(strID);
                SPListItem item = lst.Items.GetItemById(idChantier);

                Annonce ann = new Annonce();
                ann.ID = item.ID.ToString();
                ann.LinkDetail = ParamSharepointSite + "/syndicats/Pages/" + lst + "NewsDetail.aspx";

                ann.Titre = VPLink2013SPHelper.GetValue(item, "Titre");
                ann.TitrePiwik = ann.Titre.Replace("/", "-").Replace("'", "\\'").Replace("\"", "\\'");
                ann.Chapeau = VPLink2013SPHelper.GetValue(item, "Chapeau");
                ann.Body = VPLink2013SPHelper.GetValue(item, "Description");
                ann.DatePublication = VPLink2013SPHelper.GetValueDate(item, "Date publication");

                ann.Attachments = FormatDetailAttachments(item, false);
                /*
                if (lst.Title == "CGT")
                {
                    ann.Surtitre = "CGT";
                }
                if (lst.Title == "CFDT")
                {
                    ann.Surtitre = "CFDT";
                }
                */
                ann.Surtitre = lst.Title;
                ann.Photo1 = VPLink2013SPHelper.GetValuePhoto(item, "Photo");
                ann.Attachments = FormatDetailAttachments(item, false);

                ContextTrace.AddTrace("ann.ID : " + ann.ID);
                ContextTrace.AddTrace("ann.Titre : " + ann.Titre);
                ContextTrace.AddTrace("ann.Chapeau : " + ann.Chapeau);
                ContextTrace.AddTrace("ann.Photo1 : " + ann.Photo1);
                ContextTrace.AddTrace("ann.Surtitre : " + ann.Surtitre);

                global.ListeAnnonces.Add(ann);
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("Error.ProcessSyndicatsDetail : " + exc.Message + "/" + exc.StackTrace);
            }
        }
    }
}

